package ltd.sshine.websocket.Util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


public class MapUtil {

   private static final ObjectMapper mapper=new ObjectMapper();


    public Map<String, Object> getmap(Object... o) {

        if (o.length % 2 != 0) {

            throw new MapCreateException("组成的map参数必须偶数");

        }
        Map<String, Object> map = new HashMap<>();

        for (int i = 0; i < o.length; i += 2) {
            map.put((String) o[i], o[i + 1]);
        }
        return map;

    }
    public Map<String, Object> getmsg(String msg,int code, Object... o) {

        if (o.length % 2 != 0) {

            throw new MapCreateException("组成的map参数必须偶数");

        }
        Map<String, Object> map = new HashMap<>();
        map.put("msg",msg);
        map.put("code",code);
        for (int i = 0; i < o.length; i += 2) {
            map.put((String) o[i], o[i + 1]);
        }
        return map;
    }

    public void setResp(HttpServletResponse resp, Object... o) throws IOException {

        ObjectMapper mapper = new ObjectMapper();
        resp.setContentType("application/json;charset=utf-8");
        mapper.writeValue(resp.getWriter(), getmap(o));

    }

    public Map<String, Object> setmap(Map<String, Object> map, Object... o) {

        if (o.length % 2 != 0 ) {

            throw new MapCreateException("组成的map参数必须偶数");

        }


        for (int i = 0; i < o.length; i += 2) {
            map.put(String.valueOf(o[i]), o[i + 1]);
        }
        return map;
    }


    public String getJsonMap(String type,Object data,int code, Object... o){

        if (o.length % 2 != 0) {

            throw new MapCreateException("组成的map参数必须偶数");

        }
        Map<String, Object> map = new HashMap<>();
        map.put("type",type);
        map.put("code",code);
        map.put("data",data);
        for (int i = 0; i < o.length; i += 2) {
            map.put((String) o[i], o[i + 1]);
        }


        try {
            return mapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        return null;
    }



}
